package com.securitytrace.service.impl;

import java.util.List;

import org.hibernate.criterion.Property;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.securitytrace.model.AntiFakeCode;
import com.securitytrace.service.AntiFakeService;
import com.securitytrace.service.exception.InvalidAntiFakeCodeException;
import com.securitytrace.service.exception.ValidateCountTooMuchException;

public class AntiFakeServiceImpl extends HibernateDaoSupport implements
		AntiFakeService {

	public void add(AntiFakeCode antiFake) {
		getHibernateTemplate().save(antiFake);
	}

	@SuppressWarnings("unchecked")
	public void validate(String code) throws InvalidAntiFakeCodeException,
			ValidateCountTooMuchException {
		List<AntiFakeCode> list = getSession()
				.createCriteria(AntiFakeCode.class)
				.add(Property.forName("code").eq(code)).list();
		if(list == null || list.size() == 0) {
			throw new InvalidAntiFakeCodeException();
		}
		AntiFakeCode antiFake = list.get(0);
		long count = antiFake.getValidateCount();
		if(count > 0) {
			antiFake.setValidateCount(count + 1);
			throw new ValidateCountTooMuchException(count);
		}
	}

}
